<?php
require 'ShoppingCartMySQL.php';

class ShoppingCartAuth extends ShoppingCartMySQL
{
    public function __construct($database, $user, $password)
    {
        parent::__construct($database, $user, $password);
    }
    
    public function checkAuth($userid, $password)
    {
        $stmt = $this->databaseConnection->pdo->prepare("SELECT password FROM user WHERE userid = :userid");
        $stmt->bindParam(":userid", $userid);
        $stmt->execute();
        $result = $stmt->fetch(PDO::FETCH_OBJ);
        
        if (isset($result))
        {
            return $password == $result->password;
        }
        
        return false;
    } 
    
    public function createOrder($userid) 
    {
        $this->databaseConnection->pdo->beginTransaction();
    	$currentYear = date("Y");
        
    	try 
    	{
    	    $stmt = $this->databaseConnection->pdo->prepare("SELECT COUNT(orderid) AS numberOfOrders FROM `order` WHERE orderid LIKE CONCAT(:year, '-%')");
    	    $stmt->bindParam(":year", $currentYear);
    	    $stmt->execute();
    	    
    	    $currentMaxNumber = $stmt->fetch(PDO::FETCH_OBJ)->numberOfOrders;
    	    
    	    if (isset($currentMaxNumber))
    	    {
    	    	$this->orderid = $currentYear . "-" . ($currentMaxNumber + 1); 
    	    }
    	    else 
    	    {
    	    	$this->orderid = 1;
    	    }
    	
    	    $stmt = $this->databaseConnection->pdo->prepare("INSERT INTO `order` (orderid, userid) VALUES (:orderid, :userid)");
     	    $stmt->bindParam(":orderid", $this->orderid);
            $stmt->bindParam(":userid", $userid);
            
            //$stmt->bindParam(":datetime", DateTime::ISO8601);
            $stmt->execute();
            
            $this->databaseConnection->pdo->commit();
    	}
    	catch (PDOException $e)
    	{
    		$this->databaseConnection->pdo->rollBack();
    		die($e->getMessage());
    	}
    	
    	return $this->orderid;
    }
    
    public function display()
    {
        parent::display();
    }
}